package handler

import (
	"fmt"
	"github.com/antchfx/htmlquery"
	"github.com/gocolly/colly"
	"log"
	"strconv"
	"strings"
)

func ReListPageSizeHandler() (pageSize int) {
	c := colly.NewCollector(colly.UserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36"))

	data := map[string]string{
		"pageNo":   "1",
		"pageSize": "20",
		"sf":       "",
		"city":     "",
		"xzjd":     "",
		"qymc":     "",
	}

	c.OnRequest(func(r *colly.Request) {
		r.Headers.Set("Cookie", "JSESSIONID=A87C2BE548AF94B7CC4B9FA8E40178D0; pageSize=20; pageNo=1")
		r.Headers.Set("Content-Type", "application/x-www-form-urlencoded")

	})
	c.OnResponse(func(r *colly.Response) {
		doc, err := htmlquery.Parse(strings.NewReader(string(r.Body)))
		if err != nil {
			log.Fatal(err)
		}
		// fmt.Println(htmlquery.OutputHTML(doc, false))
		node := htmlquery.FindOne(doc, `/html/body/div[1]/div/ul/li[11]`)
		// fmt.Println(htmlquery.OutputHTML(node, false))
		pageSize, err = strconv.Atoi(htmlquery.InnerText(node))
		if err != nil {
			fmt.Println("strconv.Atoi err")
		}

	})
	c.Post("https://www.icama.cn/BasicdataSystem/companyquery/company_query.do", data)

	return
}

func ReListHandler(pageSize int) (viewcp, citys []string, err error) {
	c := colly.NewCollector(colly.UserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36"))
	// c.OnHTML("tbody", func(e *colly.HTMLElement) {
	// 	e.Request.Visit(e.Attr("onclick"))
	// })
	pageNo := strconv.Itoa(pageSize)
	data := map[string]string{
		"pageNo":   pageNo,
		"pageSize": "20",
		"sf":       "",
		"city":     "",
		"xzjd":     "",
		"qymc":     "",
	}

	c.OnRequest(func(r *colly.Request) {
		r.Headers.Set("Cookie", "JSESSIONID=A87C2BE548AF94B7CC4B9FA8E40178D0; pageSize=20; pageNo=1")
		r.Headers.Set("Content-Type", " application/x-www-form-urlencoded")

	})
	c.OnResponse(func(r *colly.Response) {
		doc, err := htmlquery.Parse(strings.NewReader(string(r.Body)))
		if err != nil {
			log.Fatal(err)
		}
		nodes := htmlquery.Find(doc, `/html/body/div[1]/table/tbody/tr`)
		for key, node := range nodes {
			if key == 0 {
				continue
			}
			viewcompany := htmlquery.FindOne(node, "./td/span/a")
			viewcompany_str := htmlquery.SelectAttr(viewcompany, "onclick")
			// fmt.Println(viewcompany_str, viewcompany_str[:len(viewcompany_str)-2][14:])
			city := htmlquery.FindOne(node, "./td[4]/span")

			citys = append(citys, htmlquery.InnerText(city))
			viewcp = append(viewcp, viewcompany_str[:len(viewcompany_str)-2][14:])
		}
	})
	c.Post("https://www.icama.cn/BasicdataSystem/companyquery/company_query.do", data)
	return
}
